package club.itstudio.itouc.controller.jw.stu

import club.itstudio.itouc.core.exception.ITOUCException
import club.itstudio.itouc.core.util.RE
import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.entity.OUCStudent
import club.itstudio.itouc.entity.OUCStudentModel
import club.itstudio.itouc.service.JwOps
import club.itstudio.itouc.util.Mysql
import club.itstudio.itouc.util.Redis
import org.springframework.web.bind.annotation.*
import java.lang.Exception
import javax.validation.Valid

@RestController
class StudentInfo(val jwOps: JwOps,
                  val redis: Redis,
                  val mysql: Mysql){
    /**
     * 获取学生信息
     */
    @GetMapping("/jw/stu/info")
    fun getStuInfo(@CookieValue token: String): Result<Any> {
        val session = jwOps.getJwSession(token)
        val userCode = session.userCode
        val student = try {
            OUCStudent.getByUserCode(userCode)
        }catch (e: Exception) {
            session.refresh()
            jwOps.getStuGradeSpecialtyInfoFromJw(session).save()
        }
        return ResultUtil.success(student)
    }

    @PostMapping("/jw/stu/info")
    fun updateStuInfo(@CookieValue token: String,
                      @Valid @RequestBody stu: OUCStudentModel): Result<Any> {
        val session = jwOps.getJwSession(token)
        // 手机号另判
        if (stu.phone.isNotEmpty()) {
            if (!RE.phone(stu.phone))
                return ResultUtil.error("手机号格式错误")
        }
        OUCStudent(session.userCode, stu.userName, stu.grade, stu.specialty, stu.phone, stu.email).save()
        return ResultUtil.success()
    }
}
